package com.example.lenovo.fragmenttest;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        Button buttonTest1 = findViewById(R.id.buttonTest1);
        button.setOnClickListener(this);
        buttonTest1.setOnClickListener(this);
        Button buttonTest2 = findViewById(R.id.buttonTest2);
        buttonTest2.setOnClickListener(this);
        replaceFragment(new RightFragment());
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button: {
                replaceFragment(new AnotherRightFragment());
                break;
            }
            case R.id.buttonTest1: {
                ((LeftFragment) getSupportFragmentManager().findFragmentById(R.id.left_fragment)).test();
            }
            case R.id.buttonTest2: {
                ((LeftFragment) getSupportFragmentManager().findFragmentById(R.id.left_fragment)).test2();
            }
            default:
                break;
        }
    }

    public void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.right_layout, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    public void test() {
        Toast.makeText(this, "碎片中调用活动的方法", Toast.LENGTH_SHORT).show();
    }
}
